package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomerException;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.pojo.SetmealDish;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    SetmealDishService setmealDishService;
    @Autowired
    SetmealMapper mapper;
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        this.save(setmealDto);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> setmealDish.setSetmealId(setmealDto.getId()));
        setmealDishService.saveBatch(setmealDishes);

    }

    @Override
    public Page<SetmealDto> pageWithDish(Integer page, Integer pageSize, String name) {
        Page<SetmealDto> pageInfo=new Page<>(page,pageSize);
        return mapper.pageWithDish(pageInfo,name);
    }

    @Override
    public void delete(Long[] ids) {
        Integer count = this.lambdaQuery().in(Setmeal::getId, ids).eq(Setmeal::getStatus, 1).count();
        if (count>0){
            throw new CustomerException("套餐中有起售的，不可删除");
        }
        this.removeByIds(Arrays.asList(ids));
        setmealDishService.update().in("setmeal_id",ids).remove();
    }

    @Override
    public SetmealDto show(Long id) {
        return mapper.show(id);
    }

    @Override
    public void updateWithDish(SetmealDto setmealDto) {
        this.updateById(setmealDto);
        setmealDishService.update().eq("setmeal_id",setmealDto.getId()).remove();
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> setmealDish.setSetmealId(setmealDto.getId()));
        setmealDishService.saveBatch(setmealDishes);
    }

}
